package feed

import (
	"context"
	"gitee.com/mootok/mootok/src/constant/strings/redis"
	"gitee.com/mootok/mootok/src/models"
	"gitee.com/mootok/mootok/src/storage/database"
	redis2 "gitee.com/mootok/mootok/src/storage/redis"
	redis3 "github.com/redis/go-redis/v9"
	"math/rand"
	"strconv"
)

func (s *Service) GetFollowVideoFeed(c context.Context, userId int, amount int64) ([]int, error) {
	err := s.PreLoadFeed(c, userId)
	if err != nil {
		return nil, err
	}
	//从返回视频信息
	redisKey := genFollowVideoFeedListKey(userId)
	videoIds, err := getFollowVideoFeedFromRedis(c, redisKey, amount)
	if err != nil {
		return nil, err
	}
	//存在则直接返回
	return videoIds, nil
}

func setFollowVideoFeed(c context.Context, redisKey string, feedRelations []models.UserVideoFeedRelation) error {
	//生成随机数存入redis中
	max := 8640.0
	min := -8640.0
	var err error
	for i := 0; i < len(feedRelations); i++ {
		score := feedRelations[i].Score
		//生成随机数
		score = score + rand.Float64()*(max-min) + min
		if err = redis2.Client.ZAdd(c, redisKey, redis3.Z{
			Score:  score,
			Member: feedRelations[i].VideoId,
		}).Err(); err != nil {
			continue
		}
	}

	//set expireTime
	err = redis2.Client.Expire(c, redisKey, redis.UserVideoFeedExpiredTime).Err()
	return err
}

func isFollowVideoFeedKeyExists(c context.Context, redisKey string) (bool, error) {
	exists, err := redis2.Client.Exists(c, redisKey).Result()
	if err != nil {
		return false, err
	}
	if exists != 0 {
		return true, nil
	}
	return false, nil
}

func getFollowVideoFeedFromRedis(c context.Context, redisKey string, amount int64) ([]int, error) {

	result, err := redis2.Client.ZPopMax(c, redisKey, amount).Result()
	if err != nil {
		return nil, err
	}
	videoIds := make([]int, len(result))
	for i := 0; i < len(videoIds); i++ {
		num, err := strconv.Atoi(result[i].Member.(string))
		if err != nil {
			return nil, err
		}
		videoIds[i] = num
	}

	//renew redis time
	err = redis2.Client.Expire(c, redisKey, redis.UserVideoFeedExpiredTime).Err()
	if err != nil {
		return nil, err
	}

	return videoIds, nil
}

func getFollowVideoFeedFromDb(userId int) ([]models.UserVideoFeedRelation, error) {
	var feedRelations []models.UserVideoFeedRelation
	if err := database.Client.Where("user_id = ?", userId).Find(&feedRelations).Error; err != nil {
		return nil, err
	}
	return feedRelations, nil
}
